function E=adapuncoding(G)

%Takes a stream of integers G and returns coding errors E

%Pseudo code:
%Read G in pairs
last=0;
M=G(1)
N=G(2)
MGol=G(3);
d=G(4);
E=zeros(M,N);
Eaux=zeros(M*N,1);
A=8;
nsamp=1;
cont=1;
nmax=4;
for i=5:2:length(G)-1
    G1=G(i);
    G2=G(i+1);
    if G1==255 %Run or EOF
        if G2~=255 %Run!
            Eaux(last+1:last+G2)=512;
            last=last+G2;
        else %EOF
            %The matrix should be full already
            if ~(last==M*N)
                disp('Reached EOF with matrix still empty or overloaded')
            end
        end
    else %Golomb coding
        k=ceil(A/nsamp);
        MGol=2^k;
        Eaux(last+1)=G1*MGol+G2;
        last=last+1;
        cont=cont+1;
        if nsamp==nmax;
           nsamp=round(nmax/2);
           A=floor(A/2);
        end
        nsamp=nsamp+1;
        A=A+invfunctionM(Eaux(last));
    end
end

%Unwrap vector to matrix
for i=1:M
   E(i,:)=Eaux(N*(i-1)+1:N*i); 
end

%If first element is 255, then: %Run
    %If second element is not 255
        %E(i,j)=512 %Code for Run
    %Else 
        %EOF
    %End
%Else
    %First element is unary part from Golomb. Knowing M_Gol (which should
    %be a passable parameter to this function), reconstruct unary part
    %Second element is reminder, reconstruct secodn part
    %E(i,j)=2^M*q + r;
%End